package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在连接服务端");
            /*
            实例化Scoket对象(建立与远端计算机连接)
            传入两个参数:
            1服务端的IP地址,用于找到对方的计算机
            2服务端口,用于找到服务端计算机上的服务端应用程序

            查看ip的方法
            1.win+r,输入cmd,输入ipconfig,看IPv4地址
             */
            socket = new Socket("localhost",8088);
            System.out.println("服务端连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            //启动线程用于读取来自服务端发送过来的消息
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();
            //向服务端发送消息
            /*
            Scoket提供了方法:
            OutputStream getOutputStream()
            通过scoket获取输出流将写出的信息发送给服务端
             */
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);//自动行刷新
            Scanner scan = new Scanner(System.in);
            while(true){
                System.out.println("请输入昵称:");
                String nickName = scan.nextLine();
                if(nickName.trim().isEmpty()){
                    System.out.println("昵称不能为空");
                }else {
                    pw.println(nickName);//将昵称发给服务端
                    break;
                }
            }

            while(true){
                String line = scan.nextLine();
                if("exit".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);//发送数据到服务端
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                socket.close();//进行了四次挥手
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
    //该线程用于负责接收服务端发送过来的消息
    private class ServerHandler implements Runnable{
        public void run(){
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while((message=br.readLine())!=null){
                    System.out.println(message);//将服务端发送过来的消息输出
                }
            } catch (IOException e) {
            }
        }
    }
}
